<template>
  <div style="margin-top: 50px">
    <el-form :model="form" :rules="rules" ref="productInfoForm" label-width="120px" class="form-inner-container" size="small">
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          style="width: 100%"
          v-model="selectProductCateValue"
          :props="{ label: 'name', value: 'id', children: 'children' }"
          :options="productCateOptions"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="form.subTitle"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select v-model="form.brandId" @change="handleBrandChange" placeholder="请选择品牌">
          <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品介绍：">
        <el-input :autoSize="true" v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="商品货号：">
        <el-input v-model="form.productSn"></el-input>
      </el-form-item>
      <el-form-item label="商品售价：">
        <el-input v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="市场价：">
        <el-input v-model="form.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="商品库存：">
        <el-input v-model="form.stock"></el-input>
      </el-form-item>
      <el-form-item label="计量单位：">
        <el-input v-model="form.unit"></el-input>
      </el-form-item>
      <el-form-item label="商品重量：">
        <el-input v-model="form.weight">
          <template #append>克</template>
        </el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="form.sort"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="small" @click="handleNext">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { fetchListWithChildren } from '@/api/productCate'
import { fetchList as fetchBrandList } from '@/api/brand'
import { ref, computed, watch } from 'vue'
import { type FormInstance } from 'element-plus'
import { useRoute } from 'vue-router'
import type { Brand } from '@/models/brand'
import type { ProductCateTree } from '@/models/productCate'
defineOptions({ name: 'ProductInfoDetail' })
const route = useRoute()
const emit = defineEmits(['nextStep', 'update:modelValue'])
const menuFrom = ref<FormInstance>()
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
})
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' },
  ],
  subTitle: [{ required: true, message: '请输入商品副标题', trigger: 'blur' }],
  productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
  brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
  description: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }],
  requiredProp: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
}
const hasEditCreated = ref(false)
const selectProductCateValue = ref<any>([])
const productCateOptions = ref<ProductCateTree[]>([])
const brandOptions = ref<Brand[]>([])
const form = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  },
})
getProductCateList()
getBrandList()
const productId = computed(() => {
  return props.modelValue.id
})
watch(productId, (newValue) => {
  if (!route.query.id) return
  if (hasEditCreated.value) return
  if (newValue === undefined || newValue == null || newValue === 0) return
  handleEditCreated()
})
watch(selectProductCateValue, (newValue) => {
  if (newValue != null && newValue.length === 2) {
    form.value.productCategoryId = newValue[1]
    form.value.productCategoryName = getCateNameById(form.value.productCategoryId)
  } else {
    form.value.productCategoryId = null
    form.value.productCategoryName = null
  }
})

//处理编辑逻辑
function handleEditCreated() {
  if (props.modelValue.productCategoryId != null) {
    selectProductCateValue.value.push(props.modelValue.cateParentId)
    selectProductCateValue.value.push(props.modelValue.productCategoryId)
  }
  hasEditCreated.value = true
}
async function getProductCateList() {
  const response = await fetchListWithChildren()
  productCateOptions.value = response.data.data
}

async function getBrandList() {
  const response = await fetchBrandList({ pageNum: 1, pageSize: 100 })
  brandOptions.value = response.data.data.list
}
function getCateNameById(id: number) {
  let name = null
  productCateOptions.value.forEach((item) => {
    const productCate = item?.children?.find((item2) => item2.id === id)
    if (productCate) {
      name = productCate.name
      return
    }
  })
  return name
}
async function handleNext() {
  await menuFrom.value?.validate()
  emit('nextStep')
}
function handleBrandChange(val: any) {
  form.value.brandName = brandOptions.value.find((item) => item.id === val)?.name
}
</script>

<style scoped>
:deep(.el-form) {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
</style>
